package pdd.netty.Handler;

import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

/**
 * @author:liyangpeng
 * @date:2020/1/14 15:01
 */
public class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        sendHttpResponse(ctx,request,new DefaultFullHttpResponse(request.protocolVersion(),HttpResponseStatus.NOT_FOUND,ctx.alloc().buffer(0)));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse response){
        HttpResponseStatus responseStatus = response.status();
        if (responseStatus.code() != 200) {
            ByteBufUtil.writeUtf8(response.content(), responseStatus.toString());
            HttpUtil.setContentLength(response, response.content().readableBytes());
        }
        boolean keepAlive = HttpUtil.isKeepAlive(request) && responseStatus.code() == 200;
        HttpUtil.setKeepAlive(response, keepAlive);
        response.headers().set("Server","pdd-netty_0.0.1");
        ChannelFuture future = ctx.writeAndFlush(response);
        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}
